<template>
    <div>
        <el-card>
            <el-form :inline="true" :model="queryForm" ref="queryFormRef">
                <el-form-item label="角色名称：" prop="name">
                    <el-input v-model="queryForm.name" clearable />
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" :disabled="loading" @click="submitForm"
                        v-has="'btn.queryRole'">查询</el-button>
                    <el-button @click="resetForm(queryFormRef)">重置</el-button>
                </el-form-item>
            </el-form>
        </el-card>
        <el-card>
            <template #header>
                <el-button icon="Plus" @click="handleAdd" v-has="'btn.addRole'">添加角色</el-button>
            </template>
            <el-table :data="records" style="width: 100%;" v-loading="loading" border>
                <el-table-column type="index" label="序号" width="80" align="center" />
                <el-table-column prop="name" label="角色名称" min-width="100" align="center" />
                <el-table-column label="操作" min-width="320" align="center">
                    <template #default="{ row }">
                        <el-button icon="User" @click="handleAllocateAcl(row)"
                            v-has="'btn.allocateACL'">分配权限</el-button>
                        <el-button icon="Edit" @click="handleEdit(row)" v-has="'btn.editRole'">编辑</el-button>
                        <el-button type="danger" icon="Delete" @click="handleDelete(row)"
                            v-has="'btn.deleteRole'">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-card>
        <el-pagination v-model:current-page="queryForm.currentPage" v-model:page-size="queryForm.pageSize"
            :page-sizes="[10, 20, 50]" layout="total, sizes, prev, pager, next, jumper" :total="total"
            @size-change="handleSizeChange" @current-change="handleCurrentChange" />

        <el-dialog :title="isEdit ? '编辑角色' : '添加角色'" v-model="dialogVisible" :close-on-click-modal="false">
            <AddOrEditRole v-if="dialogVisible" :is-edit="isEdit" :id="id" @success="onSuccess"></AddOrEditRole>
        </el-dialog>
        <el-drawer title="分配权限" v-model="drawerVisible" :close-on-click-modal="false">
            <AllocateACL v-if="drawerVisible" :id="id" @allocateSuccess="allocateSuccess"></AllocateACL>
        </el-drawer>
    </div>
</template>

<script setup lang="ts" name="Role">
import { onMounted, reactive, ref } from 'vue';
import type { RoleType } from '@/api/role/types';
import { rolePage, roleRemove } from '@/api/role';
import type { FormInstance } from 'element-plus';
import { ElMessage, ElMessageBox } from 'element-plus';
import AddOrEditRole from './components/AddOrEditRole.vue';
import AllocateACL from './components/AllocateACL.vue';

// ---------- 查询 ----------
const loading = ref(false)
const queryForm = reactive({ name: '', currentPage: 1, pageSize: 10 })
const queryFormRef = ref<FormInstance>()
let total = ref(0)
let records = ref<RoleType[]>([])

onMounted(() => submitForm())

const submitForm = async () => {
    loading.value = true
    const data = await rolePage(queryForm);
    if (data.code === 200) {
        records.value = data.data.records
        total.value = data.data.total
    }
    loading.value = false
}
const resetForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
}
const handleSizeChange = (val: number) => {
    queryForm.currentPage = 1
    queryForm.pageSize = val
    submitForm()
}
const handleCurrentChange = (val: number) => {
    queryForm.currentPage = val;
    submitForm()
}

// ---------- 添加/编辑/删除 ----------
const isEdit = ref(false)
const dialogVisible = ref(false)
const id = ref()

const handleAdd = () => {
    dialogVisible.value = true
    isEdit.value = false
}
const handleEdit = (row: RoleType) => {
    dialogVisible.value = true
    isEdit.value = true
    id.value = row.id
}
const handleDelete = async (row: RoleType) => {
    ElMessageBox.confirm(`确认删除角色【${row.name}】吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
    }).then(async () => {
        const data = await roleRemove(row.id as number)
        if (data.code === 200) {
            ElMessage.success('删除成功');
            // 如果删除的是最后一条数据需要回到上一页
            if (records.value.length === 1) {
                queryForm.currentPage -= 1
            }
            submitForm();
        } else {
            ElMessage.error('删除失败');
        }
    });
}
const onSuccess = () => {
    dialogVisible.value = false
    // 如果是新增 需要回到第一页
    if (!isEdit.value) {
        queryForm.currentPage = 1
        queryForm.name = ''
    }
    submitForm()
}

// ---------- 分配权限 ----------
const drawerVisible = ref(false)
const handleAllocateAcl = (row: RoleType) => {
    id.value = row.id
    drawerVisible.value = true
}
const allocateSuccess = () => {
    drawerVisible.value = false
    submitForm()
}
</script>

<style scoped lang="scss">
.el-card {
    margin-bottom: 20px;
    min-width: 600px;
    
    .el-form {

        .el-input {
            width: 240px;
        }

        .el-form-item {
            margin-bottom: 0;
        }
    }
}
</style>
